package com.laoli.lab38;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * thenCombine()示例：二元聚合
 */
public class ThenCombineDemo {

    public static void main(String[] args) throws InterruptedException {
        // 问：任务A、任务B各出一个随机数(1-100)，任务C计算这两个随机数的和？
        // 关键：任务A、任务B、任务C都是异步任务

        // 异步任务A
        CompletableFuture<Integer> taskA = CompletableFuture.supplyAsync(() -> {
            System.out.printf("当前线程：%s\n", Thread.currentThread().getName());
            Integer rnd1 = new Random().nextInt(100) + 1;
            System.out.println("rnd1 = " + rnd1);
            return rnd1;
        });
        // 异步任务B
        CompletableFuture<Integer> taskB = CompletableFuture.supplyAsync(() -> {
            System.out.printf("当前线程：%s\n", Thread.currentThread().getName());
            Integer rnd2 = new Random().nextInt(100) + 1;
            System.out.println("rnd2 = " + rnd2);
            return rnd2;
        });
        // 异步任务C(等待任务A、任务B完成并获取它们的结果)
        CompletableFuture<Integer> taskC = taskA.thenCombine(taskB, (rnd1, rnd2) -> rnd1 + rnd2);
        taskC.thenAccept(result->{
            System.out.println("result = " + result);
        });

        Thread.sleep(100);
    }
}
